<template>
  <div class="article-wrap curr-main">
    <div class="search-header">
      <el-form ref="currForm" :model="formSearch" :label-width="formLabelWidth" :inline="true" class="demo-form-inline">
        <el-form-item label="文章名称">
          <el-input v-model="formSearch.title" size="small" autocomplete="off" placeholder="请输入文章名称"></el-input>
        </el-form-item>
        <el-form-item label="文章类型" :label-width="formLabelWidth">
          <el-select v-model="formSearch.sort_id" placeholder="请选择文章类型">
            <el-option :label="item.type_name" :value="item.id.toString()" v-for="item in typeList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章状态" :label-width="formLabelWidth">
          <el-select v-model="formSearch.status" placeholder="请选择文章状态">
            <el-option label="未发布" value="0"></el-option>
            <el-option label="已发布" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSubmit">查询</el-button>
          <el-button size="small" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="content-table">
      <div class="content-header">
        <h3>文章列表</h3>
        <div class="header-right">
          <el-button type="primary" size="small" @click.prevent="addRow(1)"> 新增</el-button>
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column prop="title" label="文章名称" header-align="center" />
        <el-table-column prop="type_name" label="文章类型" align="center"></el-table-column>
        <el-table-column prop="create_date" label="创建时间" align="center" />
        <el-table-column prop="statusName" label="状态" align="center" width="180" />
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template #default="scope">
            <el-button type="text" size="small" @click.prevent="read(scope.row)">
              阅览
            </el-button>
            <el-button type="text" size="small" @click.prevent="editRow(scope.row)">
              修改
            </el-button>

              <el-button type="text" size="small" @click="publishRow(scope.row, '1')" v-show="scope.row.status == '0'">
                发布
              </el-button>
              <el-button type="text" size="small" @click="publishRow(scope.row, '0')" v-show="scope.row.status == '1'">
                取消发布
              </el-button>
    
            <el-button type="text" class="delete" size="small" @click.prevent="deleteRow(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
        :currentPage="pageNum" 
        :page-sizes="[10,20,30,40,50]" 
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" 
        :total="total" 
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
       >
      </el-pagination>
    </div>
    <DialogAlert :dialogVisible="dialogVisible" :alertTitle="alertTitle" :alertObj="alertObj" @closeDialog="closeDialog" />
    <read-dialog ref="addTypeRef"></read-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, reactive, toRefs } from 'vue'
import {getArticle, deleteArticle, publishArticle} from '@/api/article'
import { getTypes } from '@/api/type'
import DialogAlert from './components/DialogAlert.vue'
import readDialog from './components/read.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
export default defineComponent({
  name: 'ManagementArticles',
  components: {
    DialogAlert,
    readDialog
  },
  setup() {
    const currForm = ref(null)
    const addTypeRef = ref('addTypeRef')//新增表单实列
    //  初始化数据
    const state = reactive({
      tableData:  [],
      formSearch: {
        title: '',
        status: '',
        sort_id: ''
      },
      pageNum: 1,
      pageSize: 10,
      total: 0,
      formLabelWidth: '120px',
      dialogVisible: false,
      alertTitle: '新增文章',
      alertObj: {},
      typeList: []
    })

    onMounted(()=> {
      getTypeData()
      onSubmit()
    })

    // 查询类型数据
    const getTypeData = async()=> {
      let params = {
         pageNum: 1,
        pageSize: 1000
      }
      const { data: res } = await getTypes(params)
      if(res.code == 200) {
        const result = res.data.result;
        state.typeList = result
      }
    }
    
    // 查询
    const onSubmit = () => {
      state.pageNum = 1;
      getTableData()
    }
    // 清空
    const resetForm = () => {
      state.formSearch.title = ''
      state.formSearch.status = ''
      state.formSearch.sort_id = ''
    }

    // 获取表格数据
    const getTableData = async()=> {
      let params = {
        pageNum: state.pageNum,
        pageSize: state.pageSize,
      }
      Object.assign(params, state.formSearch)

      const {data} = await getArticle(params)
      if(data.code === 200) {
        const result = data.data.result;
        state.total = data.data.total;
        state.tableData = []
        result.forEach(item=> {
          item.statusName = item.status == '0' ? '未发布': '已发布'
          state.tableData.push(item)
        })
      }
    }
    // 选择页数
    const handleSizeChange = (val) => {
      state.pageSize = val;
      getTableData()
    }
    // 选择页码
    const handleCurrentChange = (val) => {
      state.pageNum = val
      getTableData()
    }

    // 新增弹窗
    const addRow = () => {
      state.alertTitle = '新增文章'
      state.dialogVisible = true
      state.alertObj = {}
    }
    // 阅览
    const read = (row:any)=> {
      const addTypeRefValue: any = addTypeRef.value
      addTypeRefValue.open(row.content)
    }
    // 修改弹窗
    const editRow = (row) => {
      state.dialogVisible = true
      state.alertTitle = '修改文章'
      state.alertObj = row
    }
    // 发布弹窗
    const publishRow = async (row, status) => {
      let title = ''
      if(status == '0') {
        title = '确定要取消发布该文章吗?'
      } else {
        title = '确定要发布该文章吗?'
      }

      ElMessageBox.confirm(title, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
          const res = await publishArticle({ id: row.id, status })
          if (res.data.code !== 200) {
            ElMessage({
              type: 'error',
              message: '发布失败',
            })
            return
          }
          ElMessage({
            type: 'success',
            message: '发布成功',
          })
          getTableData()
      })
    }

    // 删除
    const deleteRow = async (row) => {
      if(row.status === '1') {
        ElMessage({
          type: 'warning',
          message: '已发布的文章不能删除，请先取消发布！',
        })
        return
      }
      ElMessageBox.confirm('确定要删除该文章吗?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
          const res = await deleteArticle({ id: row.id })
          if (res.data.code !== 200) {
            ElMessage({
              type: 'error',
              message: '删除失败',
            })
            return
          }
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableData()
      })
    }
    
    // 关闭弹窗
    const closeDialog = (flag) => {
      state.dialogVisible = false
      if(flag == 2) {
         getTableData()
      }
    }

    
    return {
      currForm,
     ...toRefs(state),
      addRow,
      editRow,
      deleteRow,
      handleSizeChange,
      handleCurrentChange,
      onSubmit,
      resetForm,
      closeDialog,
      read,
      addTypeRef,
      publishRow
    }
  }
})
</script>

<style lang="scss" scoped>
.article-wrap {
  height: 100%;
}

.search-header {
  background: #fff;
  margin-bottom: 15px;
  padding-top: 22px;
  border-radius: 4px;
}
.content-table {
  background: #fff;
  border-radius: 4px;
  padding: 10px 15px;
}
.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 0 10px;
}
.delete{
  color: red;
}
</style>